Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
React "Cannot read properties of undefined" on an object

I'm guessing the problem is about it being async, and it tries to read it before the data is fetched, but that shouldn't happen. This code is same as on every tutorial. I thought useEffect and .then() are handling this. What's the problem here ? Actually on tutorials they access the data with categories.title directly, without even using categories[0]. I'm confused.

import React, { useState, useEffect } from "react";
import { useOutletContext } from "react-router-dom";
import Birimler from "../../components/birimler";
import sanityClient from "../../Client";
const Yasambilim = () => {
  const { setTitle } = useOutletContext();

  useState(() => {
    setTitle("YAŞAMBİLİM");
  }, []);

  const [categories, setCategories] = useState([]);
  
  useEffect(() => {
    sanityClient
      .fetch(
        `*[_type == "article"]{
        title,
        slug,
      }`
      )
      .then((data) => setCategories(data))
      .catch(console.error);
  }, []);

  console.log(categories); /* prints [{…}] */
  console.log(categories[0]); /* prints {slug: {…}, title: 'Test Title'} */
  console.log(
    categories[0].title
  ); /* app crashes  Cannot read properties of undefined (reading 'title') */

  return (
    <>
      <Birimler />
    </>
  );
};
export default Yasambilim;
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda